<?php

namespace App\Jobs\TSP;

use App\Models\TSP\Order;
use EasyWeChat\Factory;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Facades\Log;

/**
 * Class MessageJob
 *
 * 消息
 *
 * @package App\Jobs
 */
class MessageJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $type;
    protected $order_id;
    protected $templates = [
        'start' => 'gSIy6zapAysKcZmFW67GgaVrKgbWDxf1YN4b-cou3uQ',
        'end'   => 'cvX5YHvLBeAjcWrrGl1U-wi-uCK-iwRu6SpNY7NVD6k',
    ];

    public function __construct($type, $order_id)
    {
        $this->type     = $type;
        $this->order_id = $order_id;
    }

    /**
     * 执行任务
     */
    public function handle()
    {
        try
        {
            $config = [
                'app_id'        => env('WECHAT_TSP_MINI_PROGRAM_APP_ID'),
                'secret'        => env('WECHAT_TSP_MINI_PROGRAM_SECRET'),
                'response_type' => 'array',
                'log'           => [
                    'level' => 'debug',
                    'file'  => storage_path('logs/wechat.log'),
                ],
            ];

            if (!($order = Order::with('device')->with('member')->find($this->order_id)))
            {
                return false;
            }

            if (!in_array($this->type, array_keys($this->templates)))
            {
                return false;
            }

            if (empty($order->member->openid))
            {
                return false;
            }

            $data                              = [];
            $data['template_id']               = $this->templates[$this->type];
            $data['touser']                    = $order->member->openid;
            $data['page']                      = 'pages/index/index';
            $data['data']                      = [];
            $data['data']['thing1']            = $order->device->camp_name;
            $data['data']['character_string2'] = $order->device->code;
            $data['data']['thing18']           = $order->port + 1;
            $data['data']['thing5']            = $order->hours;
            $data['data']['date11']            = $order->start_time;

            $app = Factory::miniProgram($config);
            $app->subscribe_message->send($data);
        }
        catch (\Exception $e)
        {
            Log::error($e->getMessage() . ' in ' . $e->getFile() . ':' . $e->getLine());
        }

        return true;
    }

    /**
     * 执行失败
     *
     * @param  null  $exception
     */
    public function fail($exception = null)
    {
        echo $exception;
    }
}
